#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX_LEN 1024

int main(int argc, char **argv)
{
    FILE *fp = NULL; //操作fp相当于操作fp所指向的文件

    char buffer[1024];
    
    /**
     * mode:
     * +:读写方式打开
     * r:文件不存在，不会创建新的文件
     * w:文件存在，会清空当前文件
     * a+:文件末尾追加，不清空文件
     * b:二进制方式
     * result:
     * 失败返回NULL
    */
    fp = fopen(argv[1], "a+");
    if(NULL == fp)
    {
        printf("open file error:%s\n", argv[1]);
        perror("open file error!");
        exit(1);
    }
    
    fseek(fp, 0, SEEK_END);
    int filesize = ftell(fp);
    printf("file size = %d\n", filesize);


    //fwrite
    memset(buffer, 0, sizeof(buffer));
    memcpy(buffer, "hello world", 11);

    int w_len = fwrite(buffer, 1, strlen(buffer), fp);
    if(w_len < 0)
    {
        perror("write data error");
        exit(1);
    }

    // if(fseek(fp, 0, SEEK_SET) != 0)
    // {
    //     perror("seek fp error!");
    //     exit(1);
    // }

    // int filelen = ftell(fp);
    // fseek(fp, -filelen, SEEK_CUR);
    
    rewind(fp);
    
    //fseek(fp, 0, SEEK_END);
     
    memset(buffer, 0, sizeof(buffer));
    //fread
    int r_len = fread(buffer, 1, w_len, fp);
    if(r_len < 0)
    {
        perror("read data error");
        exit(1);
    }
    printf("r_len = %d\n", r_len);
    printf("read data:%s\n", buffer);

  



    fclose(fp);
    

    return 0;
}